package com.wholesmart.common.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.wholesmart.common.security.bean.Admin;
import com.wholesmart.mapper.entity.User;
import com.wholesmart.service.UserService;

/**
 * Spring Security通过这个类从数据库获取用户信息用于认证和鉴权
 * 
 * @author dyw
 * @date 2019年10月11日
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private UserService userService;

	/**
	 * 根据用户名从数据库查询用户信息
	 * 
	 * @param username
	 * @return
	 */
	private UserDetails getUserDetails(String username) throws UsernameNotFoundException {
		// 这里可以根据实际需求从数据库中查询相关数据，可以实现自己的UserDetails类
		User dbUser = userService.getByUsername(username);
		if (dbUser == null) {
			throw new UsernameNotFoundException("用户名不存在");
		}
		String name = dbUser.getUsername();
		String password = dbUser.getPassword();
		String enabled = dbUser.getEnabled();
		String status = dbUser.getStatus();

		/*
		 * 参数释义：1用户名，2用户密码(加密后的密码)，3用户是否禁用，4用户是否过期，5凭证是否过期，6用户是否锁定
		 */
		return new Admin(name, password, "0".equals(enabled), true, true, "0".equals(status));
	}

	/*
	 * 根据用户名获取用户信息构建UserDetails
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("表单登陆用户名：" + username);
		return getUserDetails(username);
	}

}
